package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.base.Strings;

import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.IMusicService;

import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.helper.HttpHelper;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * <p>
 * 背景音乐
 * </p>
 *
 * @author chenxuebin
 * @since 2019-12-08
 */
@Controller
public class MusicController {

    private static final Logger logger = LoggerFactory.getLogger(MusicController.class);

    @Autowired
    private IMusicService musicService;

    @RequestMapping("admin/music/index")
    public String index(Model model) {
        return "admin/music";
    }

    @RequestMapping("/admin/music/list")
    @ResponseBody
    public Page<Music> list(@RequestParam(value = "offset", required = false) Integer offset,
                                @RequestParam(value = "status", required = false) Integer status,
                                @RequestParam(value = "search", required = false) String search,
                                @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Music> wrapper = new EntityWrapper<Music>();
        wrapper.orderBy("id", true);
        Page<Music> page = musicService.selectPage(new Page<Music>(offset/limit+1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/music/add")
    public String add(@Valid Music bean, @RequestParam(value = "mfile", required = true) MultipartFile mfile) {
        // 字段校验
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 32) rfilename = rfilename.substring(0, 32);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);

            String dirpath = Constants.IMG_UPLOAD_PATH  + "mp3/" ;

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
//            String filename = EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname;
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ","").replaceAll("、","").replaceAll("-","");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 32) : newfname;
            if (newfname.length() > 32) newfname = newfname.substring(0, 32);

//            File file = new File(dirpath + EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname);// 保持原有文件格式
            File file = new File(dirpath + newfname + "." + extname);// 保持原有文件格式
            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 32);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }

            String imgurl = Constants.IMG_UPLOAD_HOST + "mp3/" + file.getName();
            logger.info("===========================imgurl=" + imgurl);
            logger.info("===========================file.getPath()=" + file.getPath());
            bean.setUrl(imgurl);
        }
        bean.setState(1);
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/music";
    }

    @RequestMapping("/admin/music/getMusicById")
    @ResponseBody
    public Music getMusicById(long id) {
        Music music = musicService.selectById(id);
        return music;
    }

    @RequestMapping("/admin/music/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = musicService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/music/changeState")
    @ResponseBody
    public String changeState(int id, int state) {
        Music bean = new Music();
        bean.setId(id);
        bean.setState(state);
        musicService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/music/modify")
    public String update(Music bean) {
        boolean isSuccc = musicService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

}
